<template>
  <div class="p-2">
    <!-- 水库注册登记管理 -->
    <!-- 查询表单 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="100px">
        <el-form-item label="水库名称" prop="reservoirName">
          <el-input v-model="queryParams.reservoirName" placeholder="请输入水库名称" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="水库编码" prop="reservoirCode">
          <el-input v-model="queryParams.reservoirCode" placeholder="请输入水库编码" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="所在地区" prop="region">
          <el-input v-model="queryParams.region" placeholder="请输入所在地区" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="水库类型" prop="reservoirType">
          <el-select v-model="queryParams.reservoirType" placeholder="请选择水库类型" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="大型" value="large" />
            <el-option label="中型" value="medium" />
            <el-option label="小型" value="small" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="全部" value="" />
            <el-option label="正常" value="1" />
            <el-option label="维护" value="2" />
            <el-option label="停用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增水库</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="hover">
      <el-table v-loading="loading" :data="reservoirList" @selection-change="handleSelectionChange" border>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="水库编码" prop="reservoirCode" width="120" align="center" />
        <el-table-column label="水库名称" prop="reservoirName" width="150" align="center" />
        <el-table-column label="所在地区" prop="region" width="150" align="center" />
        <el-table-column label="水库类型" prop="reservoirType" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getReservoirTypeTagStyle(row.reservoirType)">
              {{ getReservoirTypeLabel(row.reservoirType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="库容量(万m³)" prop="capacity" width="120" align="center" />
        <el-table-column label="管理单位" prop="managementUnit" width="150" align="center" />
        <el-table-column label="联系人" prop="contactPerson" width="100" align="center" />
        <el-table-column label="联系电话" prop="contactPhone" width="120" align="center" />
        <el-table-column label="状态" prop="status" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTagStyle(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" align="center" width="240" class-name="small-padding fixed-width" fixed="right">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button link type="primary" icon="View" @click="handleView(scope.row)">查看</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handlePagination"
        />
      </div>
    </el-card>

    <!-- 水库表单弹窗 -->
    <ReservoirFormDialog v-model="formDialogVisible" :title="formDialogTitle" :reservoir-data="currentReservoirData"
      @success="handleFormSuccess" />
  </div>
</template>

<script setup lang="ts" name="ReservoirRegistration">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { Search, Refresh, Plus, Delete, Download, Edit, View } from '@element-plus/icons-vue'
import ReservoirFormDialog from './components/ReservoirFormDialog.vue'
import Pagination from '@/components/Pagination/index.vue'

// 模拟API接口
const allData = ref<any[]>([])
const randInt = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min
const randomChoice = <T>(arr: T[]) => arr[Math.floor(Math.random() * arr.length)]

const generateMockData = (count: number) => {
  const reservoirs = ['青山水库', '绿水水库', '白云水库', '龙湖水库', '梅岭水库']
  const regions = ['北京市昌平区', '上海市浦东新区', '广州市番禺区', '杭州市西湖区', '成都市高新区']
  const types = ['large', 'medium', 'small']
  const units = ['市水务局', '省水利厅', '水务公司']
  const contacts = ['张三', '李四', '王五', '赵六', '钱七']
  const phones = ['13800138001', '13800138002', '13800138003', '13800138004', '13800138005']
  const statuses = ['1', '2', '0']
  const data: any[] = []
  for (let i = 1; i <= count; i++) {
    data.push({
      id: i,
      reservoirCode: `SK${String(i).padStart(3, '0')}`,
      reservoirName: randomChoice(reservoirs),
      region: randomChoice(regions),
      reservoirType: randomChoice(types),
      capacity: randInt(500, 10000),
      managementUnit: randomChoice(units),
      contactPerson: randomChoice(contacts),
      contactPhone: randomChoice(phones),
      status: randomChoice(statuses),
      remark: '模拟登记信息'
    })
  }
  return data
}

const applyFiltersAndPaginate = (params: any) => {
  let filtered = allData.value.slice()
  if (params.reservoirName) {
    const kw = String(params.reservoirName).trim()
    filtered = filtered.filter((i: any) => String(i.reservoirName).includes(kw))
  }
  if (params.reservoirCode) {
    const kw = String(params.reservoirCode).trim()
    filtered = filtered.filter((i: any) => String(i.reservoirCode).includes(kw))
  }
  if (params.region) {
    const kw = String(params.region).trim()
    filtered = filtered.filter((i: any) => String(i.region).includes(kw))
  }
  if (params.reservoirType) {
    filtered = filtered.filter((i: any) => i.reservoirType === params.reservoirType)
  }
  if (params.status) {
    filtered = filtered.filter((i: any) => i.status === params.status)
  }
  const total = filtered.length
  const startIndex = (params.pageNum - 1) * params.pageSize
  const rows = filtered.slice(startIndex, startIndex + params.pageSize)
  return { rows, total }
}

const getReservoirList = async (params: any) => {
  if (!allData.value.length) {
    allData.value = generateMockData(randInt(10, 50))
  }
  const { rows, total } = applyFiltersAndPaginate(params)
  return { code: 200, rows, total }
}

const deleteReservoir = async (ids: string) => {
  const idArr = ids.split(',').map(id => Number(id))
  allData.value = allData.value.filter((item: any) => !idArr.includes(Number(item.id)))
  return { code: 200, msg: '删除成功' }
}

const exportReservoir = async (params: any) => {
  return new Blob(['模拟导出数据'], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
}

// 响应式数据
const loading = ref(false)
const total = ref(0)
const multipleSelection = ref<any[]>([])
const reservoirList = ref([])

// 弹窗相关
const formDialogVisible = ref(false)
const formDialogTitle = ref('新增水库')
const currentReservoirData = ref<any | null>(null)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  reservoirName: '',
  reservoirCode: '',
  region: '',
  reservoirType: '',
  status: ''
})

// 获取水库类型标签样式
const getReservoirTypeTagStyle = (type: string) => {
  const styleMap: Record<string, string> = {
    large: 'danger',
    medium: 'warning',
    small: 'success'
  }
  return styleMap[type] || 'info'
}

// 获取水库类型标签文本
const getReservoirTypeLabel = (type: string) => {
  const labelMap: Record<string, string> = {
    large: '大型',
    medium: '中型',
    small: '小型'
  }
  return labelMap[type] || type
}

// 获取状态标签样式
const getStatusTagStyle = (status: string) => {
  const styleMap: Record<string, string> = {
    '1': 'success',
    '2': 'warning',
    '0': 'danger'
  }
  return styleMap[status] || 'info'
}

// 获取状态标签文本
const getStatusLabel = (status: string) => {
  const labelMap: Record<string, string> = {
    '1': '正常',
    '2': '维护',
    '0': '停用'
  }
  return labelMap[status] || status
}

// 查询水库列表
const getList = async () => {
  try {
    loading.value = true
    const response = await getReservoirList(queryParams)
    reservoirList.value = response.rows
    total.value = response.total
  } catch (error) {
    console.error('获取水库列表失败:', error)
    ElMessage.error('获取水库列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置
const resetQuery = () => {
  queryParams.reservoirName = ''
  queryParams.reservoirCode = ''
  queryParams.region = ''
  queryParams.reservoirType = ''
  queryParams.status = ''
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection: any[]) => {
  multipleSelection.value = selection
}

// 计算属性
const multiple = computed(() => multipleSelection.value.length === 0)

// 新增按钮操作
const handleAdd = () => {
  formDialogTitle.value = '新增水库'
  currentReservoirData.value = null
  formDialogVisible.value = true
}

// 编辑水库
const handleEdit = (row: any) => {
  formDialogTitle.value = '修改水库'
  currentReservoirData.value = row
  formDialogVisible.value = true
}

// 查看水库
const handleView = (row: any) => {
  ElMessage.info(`查看水库详情：${row.reservoirName}`)
}

// 删除按钮操作
const handleDelete = async (row?: any) => {
  const reservoirsToDelete = row ? [row] : multipleSelection.value
  if (reservoirsToDelete.length === 0) {
    ElMessage.warning('请选择要删除的水库')
    return
  }

  const reservoirIds = reservoirsToDelete.map(item => item.id)
  const reservoirNames = reservoirsToDelete.map(item => item.reservoirName).join('、')

  try {
    await ElMessageBox.confirm(
      `是否确认删除水库"${reservoirNames}"？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteReservoir(reservoirIds.join(','))
    ElMessage.success('删除成功')
    multipleSelection.value = []
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 导出按钮操作
const handleExport = async () => {
  const downloadLoadingInstance = ElLoading.service({ text: '正在导出数据，请稍候', background: 'rgba(0, 0, 0, 0.7)' })
  try {
    const reservoirsToExport = multipleSelection.value.length > 0 ? multipleSelection.value : null
    const exportData = reservoirsToExport ? {
      reservoirIds: reservoirsToExport.map(item => item.id)
    } : queryParams

    const response = await exportReservoir(exportData)
    
    // 验证是否为blob格式
    const isBlob = response.type !== 'application/json'
    if (isBlob) {
      // 生成文件名（包含时间戳）
      const now = new Date()
      const timestamp = now.getFullYear() + 
        String(now.getMonth() + 1).padStart(2, '0') + 
        String(now.getDate()).padStart(2, '0') + 
        String(now.getHours()).padStart(2, '0') + 
        String(now.getMinutes()).padStart(2, '0') + 
        String(now.getSeconds()).padStart(2, '0')
      const filename = `水库列表_${timestamp}.xlsx`
      
      // 创建blob并下载
      const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = filename
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
      
      ElMessage.success('导出成功')
    } else {
      ElMessage.error('导出失败')
    }
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    downloadLoadingInstance.close()
  }
}

// 分页处理
const handlePagination = () => {
  getList()
}

// 表单成功回调
const handleFormSuccess = () => {
  formDialogVisible.value = false
  getList()
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style scoped>

</style>